<?php
class BWeChatClass 
{
    var $appid = NULL;
    var $appsecret = NULL;
    ////验证消息
    public function valid() {
            $echoStr = $_GET["echostr"];
            
            //valid signature, option
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        }
    //签名
   private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
     //构造函数，获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }

        //hardcode
         $this->lasttime = 1395049256;
         $this->access_token = "nRZvVpDU7LxcSi7GnG2LrUcmKbAECzRf0NyDBwKlng4nMPf88d34pkzdNcvhqm4clidLGAS18cN1RTSK60p49zIZY4aO13sF-eqsCs0xjlbad-lKVskk8T7gALQ5dIrgXbQQ_TAesSasjJ210vIqTQ";

        if (time() > ($this->lasttime + 7200)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);
            //save to Database or Memcache
            $this->access_token = $result["access_token"];
            $this->lasttime = time();
        }
    }
    public function opendi_get() {
         $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
            if (empty($postStr)){
                echo "";
                exit;
            }

            //extract post data
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
        return $fromUsername;
        
    }
     public function responseMsg() {
            //get post data, May be due to the different environments
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
            if (empty($postStr)){
                echo "";
                exit;
            }

            //extract post data
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $time = time();

            //文本消息模板
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
            
            switch (strtolower(trim($postObj->MsgType))) {
                case "text": //文本消息
                    $keyword = trim($postObj->Content);
                    if(!empty($keyword)) {
                        $msgType = "text";
                        $openid = $this->opendi_get();
                        if( $keyword == "？" ||  $keyword == "?")
                        {
                            $msgType = "transfer_customer_service";
                            
                            
                        }
                        // header("Location:http://www.baidu.com");
                      
                        $contentStr = "$fromUsername,| | $openid|| $toUsername, ||$nei||您发送了文本信息: $keyword ;<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd33a8d04590d6e58&redirect_uri=http://1.hamshun.sinaapp.com/oauth2.php&response_type=code&scope=snsapi_base&state=1#wechat_redirect'>点击这里绑定</a>;菜单连接：<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd33a8d04590d6e58&redirect_uri=http://1.hamshun.sinaapp.com/oauth2.php?to=http://stage.billyn.net/index.php/site/index/device/wechat/wxsp/wxsp_2/wxop/BOperation_11/menu/ffcea1c090c789607f4baf5b6020ac9d/b_linkId/1f2be5c9dfaf53c7c436a7d2f66874f6&response_type=code&scope=snsapi_base&state=1#wechat_redirect'>酒店</a>";
                        if (strtolower($keyword) == "time") {
                            $contentStr = date("Y-m-d H:i:s", $time);
                        }
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    } else {
                        $resultStr = "Input something...";
                    }
                    break;
                case "image": //图片消息
                    $msgType = "text";
                    $contentStr = "$fromUsername, 您发送了图片信息";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    break;
                case "voice": //声音消息
                    $msgType = "text";
                    $contentStr = "$fromUsername, 您发送了声音信息";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    break;
                case "video": //视频消息
                    $msgType = "text";
                    $contentStr = "$fromUsername, 您发送了视频信息";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    break;
                case "location": //位置消息
                    $msgType = "text";
                    $contentStr = "$fromUsername, 您发送了位置信息";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    break;
                case "link": //链接消息
                    $msgType = "text";
                    $contentStr = "$fromUsername, 您发送了链接信息";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    break;
                case "event": //事件
                    switch (strtolower(trim($postObj->Event))) {
                        case "subscribe": //关注事件
                         $msgType = "text";
                         $openid = $fromUsername;
                         
                        //$contentStr = " $fromUsername, $toUsername,欢迎关注本微信号。输入“？”启用微客服！";//??????????????
                        //$openid = "oxmO-uOCfFT4MmAx0-Xu5McdDIt0";
                        //var_dump($weixin->get_user_info($openid));
                         $info = $this->get_user_info($openid);
                        //echo "name::";
                        $name = $info["nickname"]; 
                        //$info  = $weixin->get_user_info($fromUsername);
                        //$name = $info["nickname"];
                       $contentStr = "$name,欢迎关注本微信号。输入“？”启用微客服！<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appid&redirect_uri=http://1.hamshun.sinaapp.com/oauth2.php&response_type=code&scope=snsapi_base&state=1#wechat_redirect'>点击这里绑定</a>";
                             // $str =  $contentStr.$info;
                        //<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appid&redirect_uri=http://1.hamshun.sinaapp.com/oauth2.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'>点击这里绑定</a>
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        //$fromUsername ：openid
                        //$weixin->access_token :access_token
                        /*
                        $weixin->get_user_info($openid)
                        */
                            break;
                        case "unsubscribe": //取消关注事件
                        //echo "hi";
                            break;
                        case "scan": //用户已关注时扫描二维码事件
                            $msgType = "text";
                        //   $contentStr = "$fromUsername, 您扫描了二维码";
                     	   $contentStr = "扫描 ".$postObj->EventKey;
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            break;
                        case "location": //上传地理位置事件
                            $msgType = "text";
                            $contentStr = "$fromUsername, 您上传地理位置";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            break;
                      case "click": //自定义菜单事件  
                        //  $code = $_GET["code"];
                        //   $userinfo = $this->getUserInfoByCode($code);
                        // $usersopen_id = $userinfo["openid"];
                            $msgType = "text";  
                        // $url =  $postObj->EventKey."?openid=".$fromUsername;
                      		  // header('Location: http://www.baidu.com/');
                        //echo "AAAAAAAAA";
                       

                            $contentStr = "$fromUsername, 您点击了自定义菜单 $postObj->EventKey";  
                            if ("BUTTON_ZAN" == $postObj->EventKey) {  
                                $contentStr = "感谢您的赞，我们会继续提供更优质的服务。";  
                            }  
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);  
                            break; 
                        case "view":
                        break;
                        default:
                            $resultStr = "";
                    }
                    break;
                default:
                    $resultStr = "";
            }
            echo $resultStr;
        }
    
    

   

    //获取关注者列表
    public function get_user_list($next_openid = NULL)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //获取用户基本信息
    public function get_user_info($openid)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
    //网页授权
    public function getUserInfoByCode($code,$appid = NULL, $appsecret = NULL)
    {
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }
        // $appid = "wxd33a8d04590d6e58";
        // $appsecret = "6e18aba904d1e8c71995c5438ebfa4dc";
        //$access_token = "WEIXIN";
    
        //根据code获得Access Token
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
        $access_token_json =$this->https_request($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        $access_token = $access_token_array['access_token'];
        $openid = $access_token_array['openid'];
        //根据Access Token和OpenID获得用户信息
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid ";
        $userinfo_json =$this->https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json, true);
        return $userinfo_array;
    }

    //创建菜单
    public function create_menu($data)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }

    //发送客服消息，已实现发送文本，其他类型可扩展
    public function send_custom_message($touser, $type, $data)
    {
        $msg = array('touser' =>$touser);
        switch($type)
        {
            case 'text':
                $msg['msgtype'] = 'text';
                $msg['text']    = array('content'=> urlencode($data));
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
        return $this->https_request($url, urldecode(json_encode($msg)));
    }

    //生成参数二维码
    public function create_qrcode($scene_type, $scene_id)
    {
        switch($scene_type)
        {
            case 'QR_LIMIT_SCENE': //永久
                $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                break;
            case 'QR_SCENE':       //临时
                $data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        $result = json_decode($res, true);
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result["ticket"]);
    }
    
    //创建分组
    public function create_group($name)
    {
        $data = '{"group": {"name": "'.$name.'"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    
    //移动用户分组
    public function update_group($openid, $to_groupid)
    {
        $data = '{"openid":"'.$openid.'","to_groupid":'.$to_groupid.'}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    
    //上传多媒体文件
    public function upload_media($type, $file)
    {
        $data = array("media"  => "@".dirname(__FILE__).'\\'.$file);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    //高级群发(根据分组)
    public function mass_send_group($groupid,$type,$data) {
        $msg = array('filter' =>array('group_id'=>$groupid));
        $msg['msgtype'] = $type;
        switch ($type)
        {
            case 'text':
                $msg[$type] = array('content'=>$data);
                break;
            case 'image':
            case 'voice':
            case 'mpvideo':
            case 'mpnews':
                $msg[$type] = array('media_id'=>$data);
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=".$this->access_token;
        $res = $this->https_request($url, json_encode($msg));
        return json_decode($res, TRUE);
    }

    //https请求（支持GET和POST）
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}

?>
